const app = getApp()
import {
  myRequesy
} from '../../request/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight, //获取高度
    //标签选项卡数组
    tagBer: [{
        name: "最新",
        status: true,
        id: 0
      },
      {
        name: "最热",
        status: false,
        id: 1
      }
    ],
    Hizfs: false, //转发底部弹窗
    Hireveal: false, //显示隐藏底部弹窗事件
    DetailsObj: {}, //保存活动详情数据列表
    UserStatuslist: [], //用户动态数组 UserStatuslist
    cut: true, // 标签动态/流式布局切换事件
    ShowUnfold: false, //控制文本展开收起事件
    num: 0, //判断当前最新或最热动态列表
    pageNum: 1, //动态列表页码值
    nextPage: null, //判断动态列表是否有下一页数据

    pictureList: [], //标签最新/最热图片列表
    picturePgae: 1, // //最新/最热照片页码值
    pictureNum: 0, //用于判断当前是最新或最热照片列表
    nextPrcture: null, //判断照片是否有下一页数据
    follreveal: false, //控制关注状态

    stateList: [], //保存状态
    listId: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //获取缓存中的数据
    if (wx.getStorageSync('stateList')) {
      let stateList = JSON.parse(wx.getStorageSync('stateList'))
      this.setData({
        stateList
      })
    }

    this.setData({
      detailsId: options.scene ? options.scene : options.id
    })
    this.getDetailsList()

  },

  //控制文本展开收起回调
  btnUnfold() {
    this.setData({
      ShowUnfold: !this.data.ShowUnfold
    })
  },

  //返回上一页
  back() {
    wx.navigateBack()
  },


  // 最新/最热选项卡事件
  btntag(e) {
    let {
      index
    } = e.currentTarget.dataset

    let that = this
    let {
      tagBer
    } = that.data
    tagBer.forEach((item, i) => index === i ? item.status = true : item.status = false)
    this.setData({
      tagBer,
      pageNum: 1,
      picturePgae: 1
    })
    if (that.data.cut) {
      if (index === 0) {
        that.setData({
          num: 0,
        })
        that.getList()
      } else {
        that.setData({
          num: 1,
        })
        that.getList()
      }
    } else {

      if (index === 0) {
        this.setData({
          pictureNum: 0,
        })
        this.getPhotographList()
      } else {
        this.setData({
          pictureNum: 1
        })
        this.getPhotographList()
      }
    }

  },

  // 点击切换用户动态/预览图片
  SwItch() {
    let that = this
    let {
      tagBer
    } = that.data
    tagBer[0].status = true
    tagBer[0].status = false
    that.setData({
      cut: !this.data.cut
    })
    if (that.data.cut) {
      that.getList()
    } else {
      that.getPhotographList()
    }
  },
  //显示底部弹窗事件
  btnMore() {
    this.setData({
      Hireveal: true
    })
  },

  // 隐藏底部弹窗事件
  btnCancel() {
    this.setData({
      Hireveal: false,
      Hizfs: false,
      follreveal: false
    })
  },

  // 用户动态转发事件
  btnForward(e) {
    let arr = this.data.UserStatuslist[e.currentTarget.dataset.index].img_list
    this.setData({
      Hizfs: true,
      arr,
      nickName: e.currentTarget.dataset.name,
      avatarUrl: e.currentTarget.dataset.url,
      qrcodeId: e.currentTarget.dataset.id,
      Index: e.currentTarget.dataset.index,
      Isown: e.currentTarget.dataset.isown
    })
  },

  // 跳转到海报页
  headleTransmit() {
    wx.navigateTo({
      url: '/pages/transmit/transmit?arr=' + JSON.stringify(this.data.arr) + '&nickName=' + this.data.nickName + '&avatarUrl=' + this.data.avatarUrl + '&qrcodeId=' + this.data.qrcodeId
    })
  },

  // 跳转到活动报名页
  navIssue() {
    let {
      DetailsObj
    } = this.data
    let that = this
    if (DetailsObj.state === 2) {
      wx.navigateTo({
        url: '/pages/apply/apply?banner=' + DetailsObj.banner + '&sign_time=' + DetailsObj.sign_time + '&name=' + DetailsObj.name + '&tagId=' + DetailsObj.id + '&status=1',
      })
    } else if (DetailsObj.state === 0) {
      myRequesy({
        url: 'subscribe/add',
        method: 'POST',
        data: {
          tag_id: DetailsObj.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          wx.showToast({
            title: '已订阅',
          })
          that.getDetailsList()
        }
      })
    }

  },

  //  获取详情列表数据
  getDetailsList() {
    let that = this
    myRequesy({
      url: 'activity/detail',
      data: {
        tag_id: that.data.detailsId
      }
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          DetailsObj: res.data.data
        })
        if (res.data.data.state > 1) {
          this.getList()
        }
      }
    })
  },


  //点击用户头像跳转到用户动态页
  navDetail(e) {
    console.log(e);

    wx.navigateTo({
      url: '/pages/dynamic/dynamic?&id=' + e.currentTarget.dataset.id,
    })

  },


  //获取最新动态/最热动态 
  getList() {
    let that = this
    let {
      DetailsObj,
      pageNum,
      num,
    } = that.data
    myRequesy({
      url: 'tag/default-dynamics',
      data: {
        tag_id: DetailsObj.id,
        order_by: num === 0 ? 'createTime' : 'likes_count',
        page: pageNum
      }
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          UserStatuslist: res.data.data,
          nextPage: res.data.next_url
        })
      }
      console.log(res);

    })
  },


  //点击用户头像跳转到用户动态页
  navDetail(e) {
    wx.navigateTo({
      url: '/pages/dynamic/dynamic?&id=' + e.currentTarget.dataset.id,
    })

  },
  // 跳转到标签页
  btnNavTag(e) {
    console.log(e);
    if (e.currentTarget.dataset.status) {
      wx.navigateTo({
        url: '/pages/hddetails/hddetails?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.navigateTo({
        url: '/pages/tag/tag?id=' + e.currentTarget.dataset.id,
      })
    }

  },


  //点赞区域
  headlePraise(e) {
    console.log(e.currentTarget.dataset.index);
    let that = this
    let {
      UserStatuslist
    } = that.data
    if (e.currentTarget.dataset.status) {
      myRequesy({
        url: 'dynamic-likes/delete',
        method: 'POST',
        data: {
          dynamic_id: e.currentTarget.dataset.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          myRequesy({
            url: 'dynamic/detail',
            data: {
              dynamic_id: e.currentTarget.dataset.id
            }
          }).then(res => {
            if (res.data.code === 0) {
              UserStatuslist[e.currentTarget.dataset.index] = res.data.data
              that.setData({
                UserStatuslist
              })
              let {
                likes_count,
                comments_count,
                is_likes,
                id
              } = res.data.data
              that.getTrigger(likes_count, id, comments_count, is_likes)
            }
          })
        }
      })
    } else {
      myRequesy({
        url: 'dynamic-likes/add',
        method: 'POST',
        data: {
          dynamic_id: e.currentTarget.dataset.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          myRequesy({
            url: 'dynamic/detail',
            data: {
              dynamic_id: e.currentTarget.dataset.id
            }
          }).then(res => {
            if (res.data.code === 0) {
              UserStatuslist[e.currentTarget.dataset.index] = res.data.data
              that.setData({
                UserStatuslist
              })
              let {
                likes_count,
                comments_count,
                is_likes,
                id
              } = res.data.data
              that.getTrigger(likes_count, id, comments_count, is_likes)
            }
          })
        }
      })
    }
  },



  //获取当前点击动态的状态
  getTrigger(likes_count, id, comments, is_likes) {
    let that = this
    let {
      stateList
    } = that.data
    let obj = {
      likes_count,
      id,
      comments,
      is_likes
    }
    if (stateList.find(item => item.id == id) !== undefined) {
      stateList.splice(stateList.findIndex(item => item.id == id), 1)
    }
    stateList.push(obj)
    this.setData({
      stateList
    })
    wx.setStorageSync('stateList', JSON.stringify(stateList))
  },

  //用户修改后的状态
  getSlist() {
    let that = this
    let {
      UserStatuslist
    } = that.data
    //判断缓存中的数据Id是否和data中的数据Id一样 删除对应的 
    if (JSON.parse(wx.getStorageSync('deleteId') !== '')) {
      let deleteId = JSON.parse(wx.getStorageSync('deleteId'))
      for (let i = UserStatuslist.length - 1; i >= 0; i--) {
        deleteId.forEach(item => {
          if (UserStatuslist[i].id.toString() == item.toString()) {
            UserStatuslist.splice(i, 1)
          }
        })
      }
    }
    if (JSON.parse(wx.getStorageSync('stateList') !== '')) {
      let arr = JSON.parse(wx.getStorageSync('stateList'))

      //判断缓存中的数据Id是否和data中的数据Id一样 点赞 评论  
      arr.find(item => {
        UserStatuslist.find(item1 => {
          if (item.id.toString() == item1.id.toString()) {
            item1.is_likes = item.is_likes
            item1.likes_count = item.likes_count
            item1.comments_count = item.comments
          }

        })
      })
    }

    if (wx.getStorageSync('listId') !== '') {
      let listId = wx.getStorageSync('listId')
      UserStatuslist.find(item => {
        listId.find(item1 => { //关注
          if (item.user.id.toString() == item1.id.toString()) {
            item.follow_state = item1.follow_state
          }
        })
      })

    }

    that.setData({
      UserStatuslist
    })
  },

  //点击评论跳转到动态详情页
  navComm(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/details/details?status=true&id=' + id,
    })

  },
  // 点击空白区域跳转到动态详情
  headleNavComm(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/details/details?&id=' + id,
    })
  },
  // 预览动态图片
  btnPreview(e) {
    console.log(e);
    let current = e.currentTarget.dataset.item1
    let urls = e.currentTarget.dataset.item
    wx.previewImage({
      current,
      urls
    })
  },


  //下拉加载获取最新/最热动态下一页数据
  getNewestPageList() {
    let that = this
    let DetailsObj = that.data.DetailsObj
    if (that.data.nextPage !== null) {
      that.data.pageNum += 1
      myRequesy({
        url: 'tag/default-dynamics',
        data: {
          tag_id: DetailsObj.id,
          order_by: that.data.num === 0 ? 'createTime' : 'likes_count',
          page: that.data.pageNum
        }
      }).then(res => {
        if (res.data.code === 0) {
          that.setData({
            UserStatuslist: [...that.data.UserStatuslist, ...res.data.data],
            nextPage: res.data.next_url
          })
        }
      })
    }

  },


  //获取标签图片最新/最热列表
  getPhotographList() {
    let that = this
    let DetailsObj = that.data.DetailsObj
    myRequesy({
      url: 'tag/album-dynamics',
      data: {
        tag_id: DetailsObj.id,
        order_by: that.data.pictureNum === 0 ? 'createTime' : 'likes_count',
        page: that.data.picturePgae
      }
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          pictureList: res.data.data,
          nextPrcture: res.data.next_url
        })
      }
    })
  },

  //下拉加载获取最新/最热照片下一页数据
  getPhotograpPagehList() {
    let that = this
    let DetailsObj = that.data.DetailsObj
    if (that.data.nextPrcture !== null) {
      that.data.picturePgae += 1
      myRequesy({
        url: 'tag/album-dynamics',
        data: {
          tag_id: DetailsObj.id,
          order_by: that.data.pictureNum === 0 ? 'createTime' : 'likes_count',
          page: that.data.picturePgae
        }
      }).then(res => {
        if (res.data.code === 0) {
          that.setData({
            pictureList: [...that.data.pictureList, ...res.data.data],
            nextPrcture: res.data.next_url
          })
        }
      })
    }
  },


  //关注回调
  btnpay(e) {
    let that = this
    that.setData({
      userId: e.currentTarget.dataset.id,
      activeIndex: e.currentTarget.dataset.index,
      dtId: e.currentTarget.dataset.dtid
    })
    if (e.currentTarget.dataset.status) {
      that.setData({
        follreveal: true,
      })
    } else {
      let {
        UserStatuslist,
        activeIndex,
        userId,
        dtId
      } = that.data
      myRequesy({
        url: 'follow/add',
        method: 'POST',
        data: {
          user_id: userId
        }
      }).then(res => {
        if (res.data.code === 0) {
          myRequesy({
            url: 'dynamic/detail',
            data: {
              dynamic_id: dtId
            }
          }).then(res => {
            if (res.data.code === 0) {
              UserStatuslist[activeIndex] = res.data.data
              that.setData({
                UserStatuslist
              })
              // 关注
              UserStatuslist.forEach(item => {
                if (item.user.id == res.data.data.user.id) {
                  item.follow_state = res.data.data.follow_state
                }
              })
              that.setData({
                UserStatuslist
              })
              // 关注
              let {
                listId
              } = that.data
              let obj = {
                id: res.data.data.user.id,
                follow_state: res.data.data.follow_state
              }
              if (listId.find(item => item.id == obj.id) !== undefined) {
                listId.splice(listId.findIndex(item1 => item1.id == obj.id), 1)
              }
              listId.push(obj)
              that.setData({
                listId
              })
              wx.setStorageSync('listId', listId)
            }
          })
        }
      })
    }

  },

  // 确定取消关注
  headleConfirm() {
    let that = this
    let {
      userId,
      dtId,
      activeIndex,
      UserStatuslist
    } = that.data
    myRequesy({
      url: 'follow/take-off',
      method: 'POST',
      data: {
        user_id: userId
      }
    }).then(res => {
      if (res.data.code === 0) {
        myRequesy({
          url: 'dynamic/detail?dynamic_id',
          data: {
            dynamic_id: dtId
          }
        }).then(res => {
          if (res.data.code === 0) {
            UserStatuslist[activeIndex] = res.data.data
            that.setData({
              UserStatuslist,
              follreveal: false
            })
            // 关注
            UserStatuslist.forEach(item => {
              if (item.user.id == res.data.data.user.id) {
                item.follow_state = res.data.data.follow_state
              }
            })
            that.setData({
              UserStatuslist
            })

            // 关注
            let {
              listId
            } = that.data
            let obj = {
              id: res.data.data.user.id,
              follow_state: res.data.data.follow_state
            }
            if (listId.find(item => item.id == obj.id) !== undefined) {
              listId.splice(listId.findIndex(item1 => item1.id == obj.id), 1)
            }
            listId.push(obj)
            that.setData({
              listId
            })
            wx.setStorageSync('listId', listId)
          }
          wx.showToast({
            title: '已取消',
          })
        })

      }
    })
  },

  //转发海报
  headlePoster(e) {
    let {
      id,
      cardImg,
      name
    } = this.data.DetailsObj
    wx.navigateTo({
      url: '/pages/poster/poster?id=' + id + '&name=' + name + '&backImg=' + cardImg,

    })
  },
  // 获取我的用户信息
  getUserinfo() {
    let that = this
    myRequesy({
      url: 'user/info',
    }).then(res => {
      if (res.data.code === 0) {
        that.setData({
          nickName: res.data.data.nickName,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getSlist()
    this.getUserinfo()
    this.getSlist()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getNewestPageList()
    this.getPhotograpPagehList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from == "menu") {
      return {
        title: `${this.data.nickName}邀请你参与${this.data.DetailsObj.name}主题赛，赢千元大奖`,
        path: "/pages/hddetails/hddetails?id=" + this.data.detailsId,
        imageUrl: this.data.DetailsObj.banner
      }
    }
    return {
      title: this.data.Isown ? "我发布了一组作品，快来帮我点个赞" : "这组摄影作品很精彩，快来一起围观",
      path: "/pages/details/details?id=" + this.data.qrcodeId,
      imageUrl: this.data.UserStatuslist[this.data.Index].img_list[0]
    }
  }
})